#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <string.h>

#define BUF_SIZE 200

const int MESSAGE_SIZE = 200;
static int CURRENT_BUF_SIZE;
static char * buf[BUF_SIZE];
FILE *file;

static int SESSION_TRACKER; //Keeps track of session

void get_time()
{
    time_t t;

    time(&t);
    buf[CURRENT_BUF_SIZE] = (char*)malloc(strlen(ctime(&t))+ MESSAGE_SIZE);

    snprintf(buf[CURRENT_BUF_SIZE], strlen(ctime(&t)), "%s ", ctime(&t));
}

void print_log(char* filename, int line, char *fmt,...)
{
    va_list list;
    char *p, *string_value;
    int int_value;

    get_time();
    strcat(buf[CURRENT_BUF_SIZE], " ");

    va_start(list, fmt);

    for (p = fmt; *p; ++p)
    {
        if (*p != '%') //If simple string
        {
            char temp[2];
            temp[0] = *p;
            temp[1] = '\0';
            strcat(buf[CURRENT_BUF_SIZE], temp);
        }
        else
        {
            switch (*++p)
            {
                // string
                case 's':
                {
                    string_value = va_arg(list, char *);

                    strcat(buf[CURRENT_BUF_SIZE], string_value);
                    strcat(buf[CURRENT_BUF_SIZE], " ");
                    continue;
                }

                // integer
                case 'd':
                {
                    int_value = va_arg(list, int);

                    char temp[20];
                    itoa(int_value, temp, 10);
                    strcat(buf[CURRENT_BUF_SIZE], temp);
                    strcat(buf[CURRENT_BUF_SIZE], " ");
                    continue;
                }

                default:
                {
                    strcat(buf[CURRENT_BUF_SIZE], p);
                    strcat(buf[CURRENT_BUF_SIZE], " ");
                }
            }
        }
    }
    char temp[MESSAGE_SIZE];
    sprintf(temp, "[%s][line: %d] ", filename, line);
    strcat(buf[CURRENT_BUF_SIZE], temp);
    printf("%s\n", buf[CURRENT_BUF_SIZE]);

    va_end(list);

    if (SESSION_TRACKER > 0)
        file = fopen("log.txt", "a+");
    else
        file = fopen("log.txt", "w");

    if (CURRENT_BUF_SIZE < BUF_SIZE-1)
        CURRENT_BUF_SIZE++;
    else
    {
        int i;
        for (i = 0; i < BUF_SIZE; i++)
        {
            fprintf(file, "%s\n", buf[i]);
        }
        CURRENT_BUF_SIZE = 0;
    }
    SESSION_TRACKER++;
    fclose(file);
}






